import {getShopCartList, setShopCartList} from "@/utils/authCartList";

const actions = {
    addGood(context, good) {
        context.commit("addGood", good)
    },
    changeGoodState(context, good) {
        context.commit("changeGoodState", good)
    },
    changeGoodCount(context, good) {
        context.commit("changeGoodCount", good)
    },
    addGoodCount(context, good) {
        context.commit("addGoodCount", good)
    },
    subGoodCount(context, good) {
        context.commit("subGoodCount", good)
    },
    deleteGood(context, id) {
        context.commit("deleteGood", id)
    }
}
const mutations = {
    addGood(state, good) {
        const findGood = state.shopcartList.find(item => item.goods_id === good.goods_id)
        if (findGood) {
            findGood.goods_count += 1
        } else {
            state.shopcartList.unshift(good)
        }
        setShopCartList(state.shopcartList)
    },
    changeGoodState(state, good) {
        const findGood = state.shopcartList.find(item => item.goods_id === good.goods_id)
        findGood.goods_state = !findGood.goods_state
    },
    changeGoodCount(state, good) {
        const findGood = state.shopcartList.find(item => item.goods_id === good.goods_id)
        findGood.goods_count = good.goods_count
    },
    addGoodCount(state, good) {
        const findGood = state.shopcartList.find(item => item.goods_id === good.goods_id)
        findGood.goods_count = good.goods_count
    },
    subGoodCount(state, good) {
        const findGood = state.shopcartList.find(item => item.goods_id === good.goods_id)
        findGood.goods_count = good.goods_count
    },
    deleteGood(state, id) {
        state.shopcartList = state.shopcartList.filter(item => item.goods_id !== id)
    },
    changeCheckedAll(state, checked) {
        state.shopcartList.forEach(item => item.goods_state = checked)
    }
}
const state = () => {
    return {
        /*
        * 购物车的数组，用来存储购物车中每个商品的信息对象
        * 每个商品的信息对象都包含:{goods_id:ID,goods_price:价格,goods_count:数量,goods_small_logo:图片,goods_state:勾选状态}
        * */
        shopcartList: getShopCartList()
    }
}
const getters = {
    checkAll(state) {
        return state.shopcartList.every(item => item.goods_state)
    },
    totalPrice(state) {
        return state.shopcartList.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_price * item.goods_count, 0).toFixed(2)
    },
    count(state) {
        return state.shopcartList.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count, 0)
    }
}

export default {
    namespaced: true,
    actions,
    mutations,
    state,
    getters
}
